package com.rz.htk.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.core.exception.GlobalException;
import com.rz.htk.order.entity.Sender;
import com.rz.htk.order.entity.vo.OrderDeleteParam;
import com.rz.htk.order.mapper.SenderMapper;
import com.rz.htk.order.service.SenderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class SenderServiceImpl extends ServiceImpl<SenderMapper,Sender> implements SenderService{

    @Resource
    SenderMapper senderMapper;

    @Override
    public IPage<Sender> getPage(Sender sender) {
        QueryWrapper wrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(sender.getCommodity_code())) {
            wrapper.like("", sender.getCommodity_code());
        }
        Page<Sender> page = new Page<>(sender.getPageNo(), sender.getPageSize());
        IPage<Sender> desktopIPage = page(page, wrapper);
        return desktopIPage;
    }

    @Transactional
    public boolean saveSender(Sender sender){
        if (sender.getId() == null) {
            if (CollectionUtils.isNotEmpty(senderMapper.listSenderByCode(sender.getCommodity_code()))) {
                throw new GlobalException("订单编号【" +sender.getCommodity_code() + "】已存在！");
            }
            sender.setCreation_time(LocalDateTime.now());
            sender.setDelFlag(0);
        } else {
            List<Sender> oldSender = senderMapper.listSenderByCode(sender.getCommodity_code());
            if (CollectionUtils.isNotEmpty(oldSender) && !sender.getId().equals(oldSender.get(0).getId())) {
                throw new GlobalException("订单编号【" +sender.getCommodity_code() + "】已存在！");
            }
        }

        boolean isOk = this.saveOrUpdate(sender);
        if (!isOk) {
            throw new GlobalException("订单信息保存失败！");
        }
        return isOk;
    }

    @Override
    @Transactional
    public boolean batchDelete(OrderDeleteParam deleteParam){
        deleteParam.getIds().forEach(id -> {
            Sender sender = this.getById(id);
            if (sender != null) {
                sender.setDelFlag(1);
                boolean isOk = this.saveOrUpdate(sender);
                if (!isOk) {
                    throw new GlobalException("订单1【" + sender.getCommodity_code() + "】信息删除失败！");
                }
            } else {
                throw new GlobalException("订1单信息不存在，删除失败！");
            }
        });
        return true;
    }

}

